package qc.module.qms.service.rawdata;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import qc.common.core.constants.QmsCacheConstant;
import qc.common.core.unify.QCUnifyReturnValue;
import qc.module.qms.entity.QmsRawdataMapTable;
import qc.module.qms.repository.QmsRawdataMapTableRepository;

import java.util.List;
import java.util.Optional;

/**
 * QmsRawdataMapTableService
 *
 * @author QuCheng Tech
 * @since 2025/9/1
 */
@Service
public class QmsRawDataMapTableService {
    private static final Logger logger = LoggerFactory.getLogger(QmsRawDataMapTableService.class);

    private static final String Cache_Value_RawDataMapTable = QmsCacheConstant.CACHE_KEY_RAW_DATA_MAP_TABLE_ENTITY;

    @Autowired
    private QmsRawdataMapTableRepository repository;

    @CachePut(value = Cache_Value_RawDataMapTable)//更新缓存，不管是否有缓存数据都进行更新
    public List<QmsRawdataMapTable> cachePut() {
        logger.info("cachePut");

        return getAllFromDb();
    }

    @CacheEvict(value = Cache_Value_RawDataMapTable)//清除缓存
    public String cacheEvict() {
        logger.info("cacheEvict");
        return QCUnifyReturnValue.Success();
    }

    @Cacheable(value = Cache_Value_RawDataMapTable)
    public List<QmsRawdataMapTable> getAllWithCache() {
        logger.info("getAll");

        return getAllFromDb();
    }

    public List<QmsRawdataMapTable> getAllFromDb() {
        logger.info("getAllFromDb 从数据库中查询原始数据表对应关系");
        LambdaQueryWrapper<QmsRawdataMapTable> wrapper = new LambdaQueryWrapper<>();

        //排序，按表编码
        wrapper.orderByAsc(QmsRawdataMapTable::getTbcode);

        //查询数据
        List<QmsRawdataMapTable> ens = repository.selectList(wrapper);
        if (ens != null && ens.size() > 0x0)
            return ens;

        return null;
    }

    @Cacheable(value = Cache_Value_RawDataMapTable, key = "#tbcode")
    public QmsRawdataMapTable getRawDataMapTableWithCache(String tbcode) {
        logger.info("getRawDataMapTable");
        List<QmsRawdataMapTable> allTables = getAllWithCache();

        if (allTables != null && allTables.size() > 0x0) {
            Optional<QmsRawdataMapTable> table = allTables.stream().filter(p -> StringUtils.equalsIgnoreCase(tbcode, p.getTbcode())).findFirst();
            if (table != null && table.isPresent())
                return table.get();
        }

        return null;
    }
}
